/**
 * 
 */
package array.passed;

/**
 * @author xyyi
 *
 */
public class SpiralMatrixII {

	/**
	Mar 28 '12897 / 2147

	Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

	For example,
	Given n = 3,
	You should return the following matrix:

	[
	[ 1, 2, 3 ],
	[ 8, 9, 4 ],
	[ 7, 6, 5 ]
	]
	 */
	public int[][] generateMatrix(int n) {
		int[][] matrix = new int[n][n];
		generateMatrix(matrix, n, 1, 0);
		return matrix;
	}

	private void generateMatrix(int[][] matrix, int length, int value, int level) {
		if (length <= 0)
			return;

		if (length == 1) {
			matrix[level][level] = value;
		}

		// top
		for (int i = 0; i < length - 1; i++)
			matrix[level][level + i] = value++;

		// right
		for (int i = 0; i < length - 1; i++)
			matrix[level + i][level + length - 1] = value++;

		//bottom
		for (int i = length - 1; i > 0; i--)
			matrix[level + length - 1][level + i] = value++;

		//left
		for (int i = length - 1; i > 0; i--)
			matrix[level + i][level] = value++;

		generateMatrix(matrix, length - 2, value, level + 1);

	}

	/**
	 * 
	 */
	public SpiralMatrixII() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
